<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script type="text/javascript" src="fabric.js" ></script>
    <script type="text/javascript" src="rgbbaster.js"></script>
    <script src="jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript" src="qrcode.js"></script>
    <script src="base64.min.js"></script>
    <script src="canvas2image.js"></script>
    <style>
        input{
            width: 300px;
        }
        #c{
            border: 1px solid black
        }
    </style>

</head>
<body>
    <div style="float: left">
        <div id="qrcode" style="display: none"></div>
    </div>
    <div id="CanvasContainer" ><canvas id="c"></canvas></div>
    <div>
        <table>
            <tr><td>底图</td><td><input id="baseurl" value="http://7u2ftx.com1.z0.glb.clouddn.com/true.jpg"></td></tr>
            <tr><td>二维码内容</td><td><input id="qrcodeurl" value="http://www.ximalaya.com"></td></tr>
            <tr><td>二维码色调</td><td><input id="qrcodeColor" ></td></tr>
            <tr><td>二维码logo</td><td><input id="logourl" value="http://s1.xmcdn.com/css/img/common/default/user110.jpg"></td></tr>
            <tr><td>x:<span id="coodx">0  </span>y:<span id="coody">0</span></td><td>scale:<span id="scale"></span></td></tr>
            <tr><td><input class="save" type="button" onclick="download()" value="download"></td><td><input type="button" value="rebuild" onclick="fresh()"></td></tr>
        </table>

    </div>
</body>
<script>
    var option = new Object()
    function convertCanvasToImage(canvas) {
        var image = new Image();
        image.src = canvas.toDataURL("image/png");
        return image;
    }
    (function ($) {
        $.getUrlParam = function (name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]); return null;
        }
    })(jQuery);

    function fresh(){
        $("#CanvasContainer").html("<canvas id='c' ></canvas>");
        option.baseimg=$("#baseurl").val()
        //二维码字符串
        option.qrtext=$("#qrcodeurl").val()
        //二维码logo
        option.qricon=$("#logourl").val()
        option.qrmainColor=$("#qrcodeColor").val()
        build(option)
    }

    //下载图片
    function download(){
        downloadFile('qrcode.png', canvas.toDataURL("image/png"));
    }

    function downloadFile(fileName, content){
        var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
        save_link.href = content;
        save_link.download = fileName;
        var event = document.createEvent('MouseEvents');
        event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        save_link.dispatchEvent(event);
    }


    //rgba值转换16进制颜色代码
    function colorRGB2Hex(color) {
        if(color=="undefined")
            return "#000"
        var rgb = color.split(',');
        var r = parseInt(rgb[0].split('(')[1]);
        var g = parseInt(rgb[1]);
        var b = parseInt(rgb[2].split(')')[0]);
        var hex = "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
        return hex;
    }
    //获取图片主色调rgba 参数，图片url
    function getMianColor(baseimgurl){
        var main_color = undefined;
        //ajax 获取图片主色调
        $.ajax({
            url: "http://editor.gpagers.cn/urlToBase64.php",
            data: {url: baseimgurl},dataType: "json", async:true,
            success: function(data){
                //获取主色调
                RGBaster.colors(data.data, {
                    success: function(payload) {
                        console.log(payload)
                        main_color = payload.dominant;
                        // option.qrmainColor=colorRGB2Hex(main_color)
                        option.qrmainColor='black'
                        $("#qrcodeColor").val(colorRGB2Hex(main_color));
                        build(option)
                    }
                });
            }
        });
        return main_color;
    }
    window.onload=function oninit(){
        option.baseimg=$("#baseurl").val()
        //二维码字符串
        option.qrtext=$("#qrcodeurl").val()
        //二维码logo
        option.qricon=$("#logourl").val()
        //舞台尺寸
        option.stagewidth=500;
        option.stageheigt=500;
        //二维码尺寸
        option.qrsize=130;
        //二维码偏移量
        option.qroffsetx=0
        option.qroffsety=0;
        //二维码主色调
        option.qrmainColor=$("#qrcodeColor").val()
        //二维码logo尺寸
        option.logowidth=20;
        option.logoheight=20;
        init()
    };

    function init(){
        getMianColor($("#baseurl").val())
    }

    function build(option) {
        //底图url
        var baseimg = option.baseimg;
        //二维码内容
        var qrtext = option.qrtext;
        //二维码icon
        var qricon = option.qricon;
        //舞台大小
        var stagewidth=option.stagewidth;
        var stageheigt = option.stageheigt;
        //二维码大小
        var qrsize = option.qrsize;
        //二维码位置偏移
        var qroffsetx = option.qroffsetx;
        var qroffsety = option.qroffsety;
        //二维码主色调
        var qrmainColor = option.qrmainColor;
        //二维码logo尺寸
        var logowidth = option.logowidth;
        var logoheight = option.logoheight;
        $("#c").attr("width",stagewidth);
        $("#c").attr("height",stageheigt);
        $("#icon").attr("src",qricon);

        //从服务器load背景素材的base64url
        $.ajax({
            url: "http://editor.gpagers.cn/urlToBase64.php",
            data: {url: baseimg}, dataType: "json", async:true,
            success: function(data){
                var imgcomdata = new Image();
                imgcomdata.src = data.data
                //背景素材load完毕
                imgcomdata.onload=function () {
                    var imgcom = new fabric.Image(imgcomdata);
                    $('#qrcode').qrcode({
                        foreground: qrmainColor,
                        width: qrsize, height: qrsize,
                        correctLevel: 0,
                        text: qrtext,
                    });
                    var mycans = $("#qrcode canvas")[$("#qrcode canvas").length - 1];
                    var img = convertCanvasToImage(mycans);
                    //本地二维码绘制完毕
                    img.onload = function () {
                        canvas = new fabric.Canvas('c', {
                            hasControls: false,
                            lockMovementX: true,
                            lockMovementY: true,
                            evented: false,
                            selectable: false
                        });
                        var imgInstance = imgcom.set({
                            left: 0, top: 0,
                            scaleX: stagewidth / imgcom.width,
                            scaleY: stageheigt / imgcom.height,
                            hasControls: false,
                            lockMovementX: true,
                            lockMovementY: true,
                            evented: false,
                            selectable: false
                        });
                        canvas.add(imgInstance)
                        var imgInstance2 = new fabric.Image(img, {
                            left: (stagewidth - img.width) / 2 + qroffsetx,
                            top: (stagewidth - img.height) / 2 + qroffsety,

                        });
                        //从服务器load logo素材的base64url
                        $.ajax({
                            url: "http://editor.gpagers.cn/urlToBase64.php",
                            data: {url: qricon},dataType: "json", async:true,
                            success: function(icondata){
                                var iconimage = new Image();
                                iconimage.src = icondata.data
                                //icon素材load完毕
                                iconimage.onload=function () {
                                    var iconInstance = new fabric.Image(iconimage, {
                                        left: (stagewidth-iconimage.width/(iconimage.width/logowidth))/2+qroffsetx,
                                        top: (stagewidth-iconimage.height/(iconimage.height/logoheight))/2+qroffsety,
                                        scaleX:logowidth/iconimage.width,
                                        scaleY:logoheight/iconimage.height,
                                    });
                                    canvas.on("object:moving", function (e) {
                                        var obj = e.target;
                                        var top = obj.top;
                                        var left = obj.left;
                                        $("#coodx").html(top + "px, ")
                                        $("#coody").html(left + "px, ")
                                        $("#scale").html(obj.scaleX)
                                    })
                                    canvas.add(new fabric.Group([imgInstance2,iconInstance], {
                                        left: 0, top: 0, lockRotation: true,
                                        hasRotatingPoint: false
                                    }));
                                }
                            }// end of logo image
                        });
                    }
                }//end of back image
            }
        });
    }
</script>
</html>